/**
 * SLAM API服务
 * 提供与SLAM处理器的API交互功能
 */

import axios from 'axios'
import { buildUrls } from '../config/index.js'

// 创建SLAM API专用的axios实例
const slamApi = axios.create({
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

/**
 * SLAM会话管理API
 */
export const slamSessionApi = {
  /**
   * 获取所有会话列表
   */
  async getSessions() {
    try {
      const response = await slamApi.get(buildUrls.slamApi('/api/sessions'))
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      console.error('获取会话列表失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  },

  /**
   * 创建新会话
   * @param {string} sessionName - 会话名称（可选）
   */
  async createSession(sessionName = null) {
    try {
      const response = await slamApi.post(buildUrls.slamApi('/api/sessions'), {
        session_name: sessionName
      })
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      console.error('创建会话失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  },

  /**
   * 删除会话
   * @param {string} sessionId - 会话ID
   */
  async deleteSession(sessionId) {
    try {
      const response = await slamApi.delete(buildUrls.slamApi(`/api/sessions/${sessionId}`))
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      console.error('删除会话失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  },

  /**
   * 启动指定会话的SLAM处理
   * @param {string} sessionId - 会话ID
   */
  async startSlam(sessionId) {
    try {
      const url = buildUrls.slamApi(`/api/sessions/${sessionId}/start`)
      console.log('🔍 启动SLAM请求URL:', url)
      const response = await slamApi.post(url)
      console.log('🔍 启动SLAM响应:', response.data)
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      console.error('启动SLAM失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  },

  /**
   * 停止指定会话的SLAM处理
   * @param {string} sessionId - 会话ID
   */
  async stopSlam(sessionId) {
    try {
      const response = await slamApi.post(buildUrls.slamApi(`/api/sessions/${sessionId}/stop`))
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      console.error('停止SLAM失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  },

  /**
   * 获取指定会话的状态
   * @param {string} sessionId - 会话ID
   */
  async getSessionStatus(sessionId) {
    try {
      const response = await slamApi.get(buildUrls.slamApi(`/api/sessions/${sessionId}/status`))
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      console.error('获取会话状态失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  },

  /**
   * 获取指定会话的数据
   * @param {string} sessionId - 会话ID
   */
  async getSessionData(sessionId) {
    try {
      const response = await slamApi.get(buildUrls.slamApi(`/api/sessions/${sessionId}/data`))
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      console.error('获取会话数据失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  },

  /**
   * 添加视频帧到指定会话
   * @param {string} sessionId - 会话ID
   * @param {string} frameData - base64编码的帧数据
   */
  async addFrame(sessionId, frameData) {
    try {
      const response = await slamApi.post(buildUrls.slamApi(`/api/sessions/${sessionId}/frame`), {
        frame: frameData
      })
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      console.error('添加帧失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  },

  /**
   * 测试指定会话的SLAM处理
   * @param {string} sessionId - 会话ID
   */
  async testSlam(sessionId) {
    try {
      const response = await slamApi.post(buildUrls.slamApi(`/api/sessions/${sessionId}/test`))
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      console.error('测试SLAM失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  },

  /**
   * 获取实时SLAM数据
   * @param {string} sessionId - 会话ID
   */
  async getRealtimeSlamData(sessionId) {
    try {
      const response = await slamApi.get(buildUrls.slamApi(`/api/sessions/${sessionId}/data`))
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      console.error('获取实时SLAM数据失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  },

  /**
   * 获取SLAM轨迹数据
   * @param {string} sessionId - 会话ID
   */
  async getSlamTrajectory(sessionId) {
    try {
      const response = await slamApi.get(buildUrls.slamApi(`/api/sessions/${sessionId}/data`))
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      console.error('获取SLAM轨迹数据失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  },

  /**
   * 获取SLAM关键帧数据
   * @param {string} sessionId - 会话ID
   */
  async getSlamKeyframes(sessionId) {
    try {
      const response = await slamApi.get(buildUrls.slamApi(`/api/sessions/${sessionId}/data`))
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      console.error('获取SLAM关键帧数据失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  },

  /**
   * 获取SLAM地图点数据
   * @param {string} sessionId - 会话ID
   */
  async getSlamMapPoints(sessionId) {
    try {
      const response = await slamApi.get(buildUrls.slamApi(`/api/sessions/${sessionId}/data`))
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      console.error('获取SLAM地图点数据失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  }
}

/**
 * SLAM数据处理工具
 */
export const slamDataUtils = {
  /**
   * 将视频帧转换为base64
   * @param {HTMLVideoElement} videoElement - 视频元素
   * @param {HTMLCanvasElement} canvas - 画布元素
   * @returns {string} base64编码的帧数据
   */
  captureFrameToBase64(videoElement, canvas) {
    try {
      const ctx = canvas.getContext('2d')
      canvas.width = videoElement.videoWidth
      canvas.height = videoElement.videoHeight
      ctx.drawImage(videoElement, 0, 0)
      return canvas.toDataURL('image/jpeg', 0.8).split(',')[1] // 移除data:image/jpeg;base64,前缀
    } catch (error) {
      console.error('帧捕获失败:', error)
      return null
    }
  },

  /**
   * 格式化SLAM统计数据
   * @param {Object} stats - SLAM统计数据
   * @returns {Object} 格式化后的数据
   */
  formatStats(stats) {
    if (!stats) return null
    
    return {
      sessionId: stats.session_id,
      slamStatus: stats.slam_status,
      framesReceived: stats.frames_received || 0,
      framesProcessed: stats.frames_processed || 0,
      keyframes: stats.keyframes || 0,
      mapPoints: stats.map_points || 0,
      trajectoryLength: stats.trajectory_length || 0,
      startTime: stats.start_time,
      lastFrameTime: stats.last_frame_time,
      createdAt: stats.created_at
    }
  },

  /**
   * 格式化会话信息
   * @param {Object} session - 会话信息
   * @returns {Object} 格式化后的会话信息
   */
  formatSession(session) {
    if (!session) return null
    
    return {
      id: session.session_id,
      sessionName: session.session_id,
      status: session.slam_status,
      framesReceived: session.frames_received || 0,
      framesProcessed: session.frames_processed || 0,
      slamStarted: session.slam_started || false,
      createdAt: session.created_at,
      lastActivity: session.last_activity
    }
  }
}

export default slamSessionApi
